package com.wd.cloud.applet.config;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.function.BiConsumer;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.modelmapper.convention.NameTransformers;
import org.modelmapper.convention.NamingConventions;

/**
 * 对象映射
 */
public class ModelMapperConfig {
    private static final ModelMapper MODEL_MAPPER = new ModelMapper();

    private ModelMapperConfig() {
    }

    /**
     * npm config set prefix "E:\devTools\nodejs\node_global"
     * npm config set cache "E:\devTools\nodejs\node_cache"
     */

    public static <T> T mapTo(Class<T> targetClass, Object source) {
        return source == null ? null : MODEL_MAPPER.map(source, targetClass);
    }

    public static void mapTo(Object source, Object destination) {
        MODEL_MAPPER.map(source, destination);
    }

    public static <T, U> List<U> mapList(Collection<T> sourceList, Class<U> targetClass) {
        return mapList(sourceList, targetClass, (BiConsumer)null);
    }

    public static <T, U> List<T> mapList(Collection<T> sourceList, Class<U> targetClass, BiConsumer<Object, Object> convert) {
        List<T> items = new ArrayList();
        if (sourceList == null) {
            return items;
        } else {
            Iterator var4;
            Object source;
            Object item;
            if (convert != null) {
                var4 = sourceList.iterator();

                while(var4.hasNext()) {
                    source = var4.next();
                    item = mapTo(targetClass, source);
                    convert.accept(source, item);
                    items.add((T) item);
                }
            } else {
                var4 = sourceList.iterator();

                while(var4.hasNext()) {
                    source = var4.next();
                    item = mapTo(targetClass, source);
                    items.add((T) item);
                }
            }

            return items;
        }
    }

    static {
        MODEL_MAPPER.getConfiguration().setSourceNamingConvention(NamingConventions.JAVABEANS_ACCESSOR).setDestinationNamingConvention(NamingConventions.JAVABEANS_MUTATOR).setSourceNameTransformer(NameTransformers.JAVABEANS_ACCESSOR).setDestinationNameTransformer(NameTransformers.JAVABEANS_MUTATOR).setMatchingStrategy(MatchingStrategies.STRICT).setSkipNullEnabled(true);
    }
}
